<?php
namespace common\modules\storage\models;

use Yii;
use yii\behaviors\TimestampBehavior;

/**
 * This is the model class for table "key_storage_item".
 *
 * @property integer $key
 * @property integer $value
 * @author Xuegui Yuan <yuanxuegui@163.com>
 */
class KeyStorageItem extends \yii\db\ActiveRecord
{

    const CACHE_PREFIX = 'config_';

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%key_storage_item}}';
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::className()
            ]
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [
                [
                    'key',
                    'value'
                ],
                'required'
            ],
            [
                [
                    'key'
                ],
                'string',
                'max' => 128
            ],
            [
                [
                    'value',
                    'remark'
                ],
                'safe'
            ],
            [
                [
                    'key'
                ],
                'unique'
            ]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'key' => Yii::t('common', 'Key'),
            'value' => Yii::t('common', 'Value'),
            'remark' => Yii::t('common', 'Remark')
        ];
    }

    public static function getModel($key, $fromCache = true)
    {
        $cacheKey = self::CACHE_PREFIX . $key;
        
        $value = $fromCache ? getCache($cacheKey) : false;
        
        if ($value === false) {
            $value = KeyStorageItem::findOne([
                'key' => $key
            ]);
            if ($value !== null) {
                setCache($cacheKey, $value);
            }
        }
        return $value;
    }

    public static function getValue($key, $fromCache = true)
    {
        $model = self::getModel($key, $fromCache);
        if ($model === null) {
            return '不存在配置项：' . $key;
        }
        return $model->value;
    }

    public static function clearCachedConfig($key)
    {
        $cacheKey = self::CACHE_PREFIX . $key;
        deleteCache($cacheKey);
    }

    public function clearCache()
    {
        self::clearCachedConfig($this->key);
    }
}
